package com.example.demo.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.annotation.IgnoreAuth;
import com.example.demo.entity.pojo.UserVo;
import com.example.demo.entity.pojo.Users;
import com.example.demo.service.IUsersService;
import com.example.demo.utils.R;
import com.example.demo.utils.TokenUtil;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-01-09
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private IUsersService usersService;
    @IgnoreAuth
    @GetMapping("/login")
    public R login(String username, String password){
        System.out.println(username+" "+password);
        Users users = usersService.getOne(new QueryWrapper<Users>().eq("username",username));
        if(users==null||!(users.getPassword().equals(password))){
            return R.error("用户名或密码错误");
        }
        String token = TokenUtil.createToken(username);
        UserVo userLoginVO = BeanUtil.copyProperties(users,UserVo.class);
        userLoginVO.setToken(token);
        System.out.println(userLoginVO);
        Map<String,Object> map = new HashMap<>();
        map.put("data",userLoginVO);
        map.put("msg","登录成功");
        map.put("code",200);
        return R.ok(map);
    }
    @GetMapping("/getUser")
    public R getUser(){
        List<Users>  user = usersService.getById1();
        Map<String,Object> map = new HashMap<>();
        map.put("users",user);
        map.put("code",200);
        return R.ok(map);
    }
    @IgnoreAuth
    @PostMapping( "/register")
    public R register(@RequestBody Users user){
//    	ValidatorUtils.validateEntity(user);
        if(usersService.getOne(new QueryWrapper<Users>().eq("username", user.getUsername())) !=null) {
            return R.error("用户已存在");
        }
        usersService.save(user);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","注册成功");
        map.put("code",200);
        map.put("data",null);
        return R.ok(map);
    }
}
